package com.university.mentalhealthplatform.global.rbac.service.relation;

import com.university.mentalhealthplatform.global.rbac.dto.normal.MenuHierarchyDTO;
import com.university.mentalhealthplatform.global.rbac.dto.normal.PermissionDTO;
import com.university.mentalhealthplatform.global.rbac.model.ButtonComponent;
import com.university.mentalhealthplatform.global.rbac.model.Menu;
import com.university.mentalhealthplatform.global.rbac.model.Permission;
import com.university.mentalhealthplatform.global.rbac.repository.ButtonComponentRepository;
import com.university.mentalhealthplatform.global.rbac.repository.MenuRepository;
import com.university.mentalhealthplatform.global.rbac.repository.PermissionRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Set;
import java.util.stream.Collectors;

@Service
public class MenuPermissionService {

    @Autowired
    private MenuRepository menuRepository;

    @Autowired
    private ButtonComponentRepository buttonComponentRepository;


    //////////////////////////
    ///
    /// 复杂方法
    ///
    /////////////////////////
    // 递归地构建菜单层次结构
    public Set<MenuHierarchyDTO> getMenuHierarchy() {
        // 获取所有顶级菜单（parentMenu 为 null）
        Set<Menu> rootMenus = menuRepository.findByParentMenuIsNull();

        // 构建 DTO 层级结构
        return rootMenus.stream()
                .map(this::buildMenuHierarchy)
                .collect(Collectors.toSet());
    }

    // 递归函数：构建单个菜单的层次结构
    private MenuHierarchyDTO buildMenuHierarchy(Menu menu) {
        // 获取菜单的权限
        Set<ButtonComponent> buttonComponents = buttonComponentRepository.findByParentMenu(menu);

        Set<PermissionDTO> permissionDTOs = menu.getPermissions(buttonComponents).stream()
                .map(this::convertToPermissionDTO)
                .collect(Collectors.toSet());

        // 获取子菜单，并递归构建它们的层次结构
        Set<MenuHierarchyDTO> childMenuDTOs = menu.getChildMenus().stream()
                .map(this::buildMenuHierarchy)  // 递归调用
                .collect(Collectors.toSet());

        // 构建 MenuHierarchyDTO
        return new MenuHierarchyDTO(menu.getId(), menu.getIdentifier(),menu.getDisplayName(),menu.getOrderNum(),menu.isVisible(), menu.isStatus(),menu.getDescription(), permissionDTOs, childMenuDTOs);
    }

    // 辅助方法：将 Permission 转为 PermissionDTO
    private PermissionDTO convertToPermissionDTO(Permission permission) {
        return new PermissionDTO(permission.getId(), permission.getIdentifier(),permission.getDisplayName(),permission.getOrderNum());
    }








}
